package it.scullino.android.actionbar;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;


public class OverviewActivity extends Activity {
	
	// Preferenze per questa app
	private SharedPreferences preferences;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Ottengo le preferenze di questa app
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        
        
        findViewById(R.idButton.show_preferences).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// Leggo username e password salvati nelle preferenze
				String username = preferences.getString("username", "n/a");
				String password = preferences.getString("password", "n/a");
				Toast.makeText(OverviewActivity.this, username + "; " + password, Toast.LENGTH_SHORT).show();
			}
		});
        
        
        findViewById(R.idButton.change_preferences).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// Modifico le preferenze
				changePreferences();
			}
		});
    }

    
	private void changePreferences() {
		// Inverto l'username
		String username = preferences.getString("username", "n/a");
		StringBuffer buffer = new StringBuffer();
		for (int i = username.length() - 1; i>=0; i--)
			buffer.append(username.charAt(i));
		
		// Sostituisco l'username vecchio con quello nuovo
		Editor editor = preferences.edit();
		editor.putString("username", buffer.toString());
		editor.commit();
		Toast.makeText(OverviewActivity.this, "Reverting string for username", Toast.LENGTH_SHORT).show();
	}

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.mainmenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.idMenu.preferences:
			// Lancio l'activity con le preferenze
			Intent intent = new Intent(OverviewActivity.this, MyPreferenceActivity.class);
			startActivity(intent);
			break;
		case android.R.id.home:
			// Lancio la main activity premendo l'icona della app
			Intent intentHome = new Intent(this, OverviewActivity.class);
			intentHome.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intentHome);
		default:
			break;
		}
		
		return true;
	}
    
    
}